package edu.fdzc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import edu.fdzc.mapper.StudentMapper;
import edu.fdzc.pojo.PageResult;
import edu.fdzc.pojo.Student;
import edu.fdzc.pojo.StudentQueryParam;
import edu.fdzc.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> list(StudentQueryParam studentQueryParam) {
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());
        List<Student> studentList = studentMapper.list(studentQueryParam);
        Page<Student> p = (Page<Student>) studentList;
        PageResult<Student> pageResult = new PageResult<>(p.getTotal(), p.getResult());
        return pageResult;
    }

    @Override
    public void save(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        student.setViolationCount((short) 0);
        student.setViolationScore((short) 0);
        studentMapper.save(student);
    }

    @Override
    public Student getById(Integer id) {
        return studentMapper.getById(id);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
    }

    @Override
    public void violation(Integer id, Short score) {
        Student student = studentMapper.getById(id);
        student.setViolationCount((short) (student.getViolationCount() + 1));
        student.setViolationScore((short) (student.getViolationScore() + score));
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }
}
